package com.media.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;

import cc.mallet.util.CommandOption.Set;
import cern.colt.Arrays;

import com.media.example.restapi.RESTSearchExample;
import com.media.model.Person;
import com.media.service.PersonService;
   
@Controller    
public class PersonController {  
   
	
	@Autowired
	private PersonService personService;
	
    @RequestMapping(value = "/person", method = RequestMethod.GET)  
	public String getPersonList(ModelMap model) {  
        model.addAttribute("personList", personService.listPerson());  
        return "output";  
    }  
    
    @RequestMapping(value = "/person/save", method = RequestMethod.POST)  
	public View createPerson(@ModelAttribute Person person, ModelMap model) {
    	JSONArray res=RESTSearchExample.getSearchResults(person.getName());
    	ArrayList<Person> listp=new ArrayList<Person>();
    	for(int i=1;i<res.length();i++)
    	{
    		Person ps= new Person();
    		ps.setId(UUID.randomUUID().toString());
    		JSONObject obj=res.getJSONObject(i);
    		ps.setName(obj.get("text").toString());
    		listp.add(ps);
    		
    	}
    	personService.updatePersonALL(listp);
    	//System.out.println(res);
    	if(StringUtils.hasText(person.getId())) {
    		personService.updatePerson(person);
    	} else {
    		personService.addPerson(person);
    	}
    	return new RedirectView("/person", true);  
    }
        
    @RequestMapping(value = "/person/delete", method = RequestMethod.GET)  
	public View deletePerson(@ModelAttribute Person person, ModelMap model) {  
        personService.deletePerson(person);  
        return new RedirectView("/person", true);  
    }    
}
